#include "pipe_prepar.h"
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include<sys/ioctl.h>

#include <linux/fb.h>
#include <fcntl.h>
#include <stdbool.h>
#include <sys/prctl.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include<atomic>

#include"v4l2_drv/v4l2_capture.h"
#include"drm_drv/drm_plane_drv.h"

//#include <QDebug>

typedef unsigned char byte;

using namespace cv;
using namespace std;


void Pipe_Prepar::start(Capture *cap0,struct drm_plane *plane){
    printf("pipe start\r\n");
    Pipe_Prepar_State now=get_status();
    if(now==pm_init){
        this->plane=plane;
        this->cap0=cap0;
        pipeThread=new std::thread(&Pipe_Prepar::prepar_thread_run,this);
    }
    else if(now==pm_stoped){
        this->plane=plane;
        this->cap0=cap0;
        re_run();
    }
    else{
        fprintf(stderr,"pipe Prepar already start\r\n");
    }
}

void Pipe_Prepar::prepar_thread_run()
{
    struct timeval last={0,0},current={0,0};
      double fps = 0;
      int count=0;
    unsigned char* databuff0;
    int datalen0;
    unsigned char* databuff1;
    int datalen1;
    cout<<"start!";
    Mat out;
    bool already_run_flag=false;

    set_status(pm_runing);
    while(true){
        if(get_status()==pm_runing){
            if(plane->bo==NULL){
                fprintf(stderr,"plane id :%d ->bo is NULL erro,plane not init",plane->plane_id);
                sleep(1);
                continue;
            }
            gettimeofday(&current,NULL);
            //current.tv_sec * 1000 + current.tv_usec / 1000;
            fps = (current.tv_sec - last.tv_sec) * 1000000
                + current.tv_usec - last.tv_usec;
            fps = fps ? 1000000.0 / fps : 0.0;
    //computer start
            Frame tmp0=cap0->getLastFrame();
            databuff0=tmp0.data;
            datalen0   =  tmp0.height*tmp0.width*tmp0.channels/tmp0.split;


    //        usleep(20*1000);
            count++;
            if(count%60==0){
//            printf("Prepar Prepar plane:%d :fps%f\n",plane->plane_id,fps);
        //        fflush(stdout);
            }
            last=current;
            already_run_flag=true;
        }
        else{
            if(already_run_flag){
                already_run_flag=false;
                set_status(pm_stoped);
            }
            usleep(100*1000);
        }
    }
    printf("pipe Prepar critical erro");
    return;
}
